const express = require('express')
const app = express()
const port = 80
const sqlite3 = require('sqlite3')
const db = new sqlite3.Database('db\\db.sqlite3')

app.use(express.static('public'))

app.get('/api/group', (req, res) => {
  // http://localhost/api/group

  db.all('SELECT `group` FROM bookmark group by `group`', (err, rows) => {
    res.send(rows.reverse())
  })

})

app.get('/api/data', (req, res) => {
  // http://localhost/api/data?group=默认
  // http://localhost/api/data

  if (!req.query.group) {
    res.send([])
  } else {
    let sqlString = 'SELECT * FROM `bookmark` WHERE `group`=' + `"${req.query.group}"`
    db.all(sqlString, (err, rows) => {
      res.send(rows)
    })
  }

})

app.get('/api/insert', (req, res) => {
  // http://localhost/api/insert?title=百度&url=http://baidu.com&icon=pure/default.png&group=默认

  if (req.query.title || req.query.url || req.query.icon || req.query.group) {
    let sqlString = 'INSERT INTO bookmark (title, url, icon, `group`) VALUES ' + `("${req.query.title}","${req.query.url}","${req.query.icon}","${req.query.group}")`
    db.run(sqlString, (err) => {
      res.send({ "status": 200 })
    })
  } else {
    res.send({ "status": 400 })
  }

})

app.get('/api/delete', (req, res) => {
  // http://localhost/api/delete?id=10

  if (!req.query.id) {
    res.send({ "status": 400 })
  } else {
    let sqlString = 'DELETE FROM `bookmark` WHERE id=' + `${req.query.id}`
    db.run(sqlString, (err) => {
      console.log(err)
      res.send({ "status": 200 })
    })
  }

})

app.get('/api/update', (req, res) => {
  // http://localhost/api/update?id=2&title=百度&url=http://baidu.com&icon=pure/default.png&group=默认

  if (req.query.title || req.query.url || req.query.icon || req.query.group) {
    let sqlString = 'UPDATE `bookmark` SET ' + `title="${req.query.title}", url="${req.query.url}", icon="${req.query.icon}", ` + '`group`=' + `"${req.query.group}" WHERE id=${req.query.id}`
    db.run(sqlString, (err) => {
      res.send({ "status": 200 })
    })
  } else {
    res.send({ "status": 400 })
  }

})

app.listen(port, () => {
  console.log(`启动成功，http://localhost:${port}`)
})